const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
require('dotenv').config();

const app = express();
const PORT = process.env.PORT || 3000;

// 中间件配置
app.use(cors({
  origin: ['http://localhost:5173', 'http://127.0.0.1:5173', 'http://localhost:5174', 'http://127.0.0.1:5174'], // Vue开发服务器地址
  credentials: true
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// 路由配置
const homeRoutes = require('./routes/home');
const categoryRoutes = require('./routes/category');
const userRoutes = require('./routes/user');
const cartRoutes = require('./routes/cart');
const goodsRoutes = require('./routes/goods');
app.use('/home', homeRoutes);
app.use('/goods', goodsRoutes); // 使用专门的商品路由
app.use('/category', categoryRoutes);
app.use('/', userRoutes);
app.use('/', cartRoutes);

// 根路径响应
app.get('/', (req, res) => {
  res.json({
    code: '1',
    msg: 'Vue3小兔鲜后端API服务运行中',
    result: {
      version: '1.0.0',
      timestamp: new Date().toISOString()
    }
  });
});

// 404处理
app.use('*', (req, res) => {
  res.status(404).json({
    code: '0',
    msg: '接口不存在',
    result: null
  });
});

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({
    code: '0',
    msg: '服务器内部错误',
    result: null
  });
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
});